// pages/newclasscirletext/newclasscirletext.js
const app = getApp()
const qiniuUploader = require("../../utils/qiniuUploader");
var utils = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    content: "", // 文本的内容
    "placeholder": "请输入文本",
    "maxlength": 100, // 最大输入长度，设置为 -1 的时候不限制最大长度
    "focus": true,
    "auto-height": true, // 是否自动增高，设置auto-height时，style.height不生效
    "adjust-position": true, // 键盘弹起时，是否自动上推页面
    "addbtn": "../../images/icon_addpic_unfocused.png",
    photoList: [],
    photourl: [],
    qiniuToken: "",
    fabuflag:false

  },
  //失去焦点时获取里面评论内容
  bindTextAreaBlur: function (e) {
    console.log(e.detail.value)
    this.setData({
      content: e.detail.value,
    })
  },
  //获取用户输入内容
  contentInput: function (e) {
    this.setData({
      content: e.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getQiniuToken();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  addbtnclick: function (e) {
    var that = this;
    var photoList = this.data.photoList;
    wx.chooseImage({
      count: 30 - that.data.photoList.length, // 默认最多上传9张
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success(res) {
        var tempFilePaths = res.tempFilePaths; // 返回选定照片的本地路径列表 
        that.setData({
          photoList: photoList.concat(tempFilePaths)
        })
      }

    })
    console.log(this.data.photoList)
  },

  deletebtnclick: function (e) {
    var index = e.currentTarget.dataset.index;
    console.log("index" + index)
    var photoList = this.data.photoList;
    photoList.splice(index, 1)
    this.setData({
      photoList: photoList,
    })

  },

  fabubtnclick: function (e) {
    
    if(this.data.fabuflag==true){
      return
    }

    if (this.data.photoList.length == 0 && this.data.content.length == 0) {
      wx.showToast({
        title: "请添加发布内容",
        icon: 'none',
        duration: 1000,
        mask: true
      })
      return
    }

    this.setData({
      photourl: []
    })

    this.setData({
      fabuflag:true
    })


    this.sendImge();
  },
  getQiniuToken: function (e) {
    var that = this;
    var data = {
      "userid": app.globalData.userId,
      "schoolid": app.globalData.schoolId,
      "appType": app.globalData.appType,
      "appKey": app.globalData.appKey,
      "timeSpan": app.globalData.timespan
    }
    wx.request({
      url: app.globalData.serverQiNiuUrl,
      data: {
        "data": JSON.stringify(data)
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
      success: function (res) {
        console.log(res);
        if (res.data.status == 0) {
          that.setData({
            qiniuToken: res.data.data.token
          })
        } else {

        }
      },
      fail: function (res) {

      },
      complete: function (res) {
        console.log('submit complete');
      }
    })
  },


  postData: function (e) {
    var that = this;
    var message = []
    for (var i = 0; i < this.data.photourl.length; i++) {
      var a = {
        "sType": 1,
        "attachmentID": 0,
        "attachmentUrl": this.data.photourl[i]
      }
      message.push(a)
    }

    var data = {
      "userid": app.globalData.userId,
      "schoolid": app.globalData.schoolId,
      "content": that.data.content,
      "data": message,
      "appType": app.globalData.appType,
      "appKey": app.globalData.appKey,
      "timeSpan": app.globalData.timespan,
      "mobileSerialnumber": ""
    }
    wx.request({
      url: app.globalData.serverUrl,
      data: {
        "data": JSON.stringify(data),
        'act': "send_show_class"
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
      success: function (res) {
        console.log(res);
        if (res.data.status == 0) {
          wx.hideNavigationBarLoading()
          wx.hideLoading()
          wx.showToast({
            title: "发布成功",
            icon: 'none',
            duration: 1000,
            mask: true
          })
          wx.navigateBack({
            url: '../classcirle/classcirleindex'
          })
        } else {
          wx.hideNavigationBarLoading()
          wx.hideLoading()
          wx.showToast({
            title: "发布失败",
            icon: 'none',
            duration: 1000,
            mask: true
          })
          that.setData({
            fabuflag:false
          })
        }
      },
      fail: function (res) {
        wx.hideNavigationBarLoading()
        wx.hideLoading()
        wx.showToast({
          title: "发布失败",
          icon: 'none',
          duration: 1000,
          mask: true
        })
        that.setData({
          fabuflag:false
        })
      },
      complete: function (res) {
        console.log('submit complete');
      }
    })
  },

  sendImge: function () {
    wx.showNavigationBarLoading() //在当前页面显示导航条加载动画
    wx.showLoading({ //显示 loading 提示框
      title: "正在发布...",
    })

    if (this.data.photoList.length > 0) {
   
      var pathList=[]
      var fileList =[];
      for (var i = 0; i < this.data.photoList.length; i++) {
        pathList.push("")
        fileList.push("")
      }
      this.setData({
        //注意这中间有个"/"在这上面耽误了半个小时
        photourl: pathList
      })

    

      var count = 0;
      for (var i = 0; i < this.data.photoList.length; i++) {
        var timestamp = Date.parse(new Date());
        timestamp = timestamp / 1000;
        var _this = this
        var filepath = this.data.photoList[i]
        var qiniuurl;
        qiniuurl = "jygy/" + "photo/" + app.globalData.schoolId + "/" + app.globalData.classid + "/" + timestamp + "/" + utils.formatDate(new Date()) + utils.wxuuid() + ".jpg"
        fileList[i]=qiniuurl
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片  
        qiniuUploader.upload(filepath, res => {
          console.log(res)
          var url = res.imageURL

          for(var j=0;j<fileList.length;j++){
            if(fileList[j]==res.fileName){
              var pathList1 = _this.data.photourl;
              pathList1[j]=url
              _this.setData({
                //注意这中间有个"/"在这上面耽误了半个小时
                photourl: pathList1
              })
            }
          } 

          count++;
          if (count == _this.data.photoList.length) {
            _this.postData()
          }

        }, (error) => {
          wx.hideNavigationBarLoading()
          wx.hideLoading()
          wx.showToast({
            title: "发布失败",
            icon: 'none',
            duration: 1000,
            mask: true
          })
          _this.setData({
            fabuflag:false
          })
          return;
        }, {
          key: qiniuurl,
          region: 'NCN',
          uptoken: _this.data.qiniuToken,
          uploadURL: 'https://up-z1.qbox.me',
          domain: app.globalData.qiniurUrl,
        })
      }
    } else {
      wx.showNavigationBarLoading() //在当前页面显示导航条加载动画
      wx.showLoading({ //显示 loading 提示框
        title: "正在发布...",
      })
      this.postData()
    }

  }
})